/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.toto.session;

import com.toto.entity.UserLocal;
import com.toto.entity.UserLocalHome;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Administrator
 */
public class AddUserBean implements SessionBean
{
  private SessionContext sessionContext;
  UserLocalHome localHome;
  UserLocal local;

  public void ejbCreate() throws CreateException
  {
    
  }
  public void setSessionContext(SessionContext sessionContext) throws EJBException, RemoteException
  {
    this.sessionContext = sessionContext;
  }

  public void ejbRemove() throws EJBException, RemoteException
  {
    // Ingored 
  }

  public void ejbActivate() throws EJBException, RemoteException
  {
    // Ingored
  }

  public void ejbPassivate() throws EJBException, RemoteException
  {
    // Ingored
  }
  public String addUserId()
  {
    String str = "0000";
    int i = 0;
    str = str + i;
    i++;
    return str;
  }
  public static InitialContext getInitialContext() throws NamingException
  {
    Properties p = new Properties();
    p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    p.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    p.setProperty(Context.PROVIDER_URL, "jnp://localhost:1099");
    return new InitialContext(p);
  }
  public void AddUser(String name)
  {
    try
    {
      String userId = addUserId();
      InitialContext ctx = getInitialContext();
      Object obj = ctx.lookup("java:comp/env/ejb/UserBean");
      localHome = (UserLocalHome) obj;
      localHome.create(userId, name, true);
//      local = (UserLocal) obj;
      Collection users = localHome.SearchByUserId(userId);
      Iterator it = users.iterator();
      while (it.hasNext())
      {
        UserLocal user = (UserLocal) it.next();
        System.out.println(user.getName());
      }
    }
    catch (Exception ex)
    {
      Logger.getLogger(AddUserBean.class.getName()).log(Level.SEVERE, null, ex);
    } 
  }
}
